package com.ledim.service;

import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.LedimBaseUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by ccx on 16/5/16.
 */
public class HeaderInterceptor implements Interceptor {

    public HeaderInterceptor() {
    }

    /**
     * @param chain
     * @return
     *
     * @throws IOException
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        String access_token = LedimSpUtils.getToken();
        Request.Builder builder = chain.request().newBuilder();
        HttpUrl url = chain.request().url();
        LogUtil.e("okhttp: url=" + url);
        Map<String, String> toSignBody = new HashMap<String, String>();
        if (!LedimBaseUtils.isEmpty(access_token)) {
            builder.addHeader("Authorization", access_token);
            LogUtil.e("okhttp: Authorization=" + access_token);
        } else {
            builder.removeHeader("Authorization");
        }
        if ("GET".equalsIgnoreCase(chain.request().method())) {
            HttpUrl newUrl = url.newBuilder()
                                .addQueryParameter("request_ts",
                                        System.currentTimeMillis() / 1000 + "")
                                .build();
            builder.url(newUrl);
        } else if ("POST".equalsIgnoreCase(chain.request().method())) {
            if (chain.request().body() instanceof FormBody) {
                FormBody body = (FormBody) chain.request().body();
                FormBody.Builder builder1 = new FormBody.Builder();
                int size = body.size();
                for (int i = 0; i < size; i++) {
                    builder1.addEncoded(body.encodedName(i), body.encodedValue(i));
                    toSignBody.put(body.name(i), body.value(i));
                }
                String time = System.currentTimeMillis() / 1000 + "";
                builder1.add("request_ts", time);
                toSignBody.put("request_ts", time);
                builder.post(builder1.build());
            }

        }
        //builder.addHeader("User-Agent", BaseParams.getInstance().getUserAgent())
        //       .addHeader("Lianjia-Channel",
        //               DeviceUtil.getChannel(MyApplication.getInstance()))
        //       .addHeader("Lianjia-Device-Id", DeviceUtil.getUUID())
        //       .addHeader("Lianjia-Version",BaseParams.getInstance().getAppVersion())
        //       .addHeader("Authorization", signString);
        return chain.proceed(builder.build());
    }

}

